package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 设备Service业务层处理
 * 
 * @author alexis
 * @date 2024-11-12
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired
    private Client client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 同步设备列表
     */
    @Override
    public void syncProductList() {
        // 创建请求对象
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();
        // 向请求对象中放入请求参数
        // 分页条件
        queryProductListRequest.setPageSize(100);
        queryProductListRequest.setCurrentPage(1);
        // 公共实例
        queryProductListRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        // 查询公共实例下的所有产品
        QueryProductListResponse response;
        try {
            response = client.queryProductList(queryProductListRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 解析结果
        if(!response.getBody().getSuccess()){
            throw new BaseException("调用IOT获取产品列表失败");
        }

        // 存储到redis中
        String jsonStr = JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo());
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST, jsonStr);
    }

    /**
     * 获取设备列表
     */
    @Override
    public List<ProductVo> getAllProject() {
        // 从redis中获取
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST);
        // 判断是否为空
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        // 解析
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto 设备信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerDevice(DeviceDto deviceDto) {
        // 判断设备名称是否重复
        Long count = deviceMapper.selectCount(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count > 0){
            throw new BaseException("设备名称重复");
        }
        // 如果不重复，调用IOT平台接口，注册设备
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if(!response.getBody().getSuccess()){
            throw new BaseException("调用IOT平台注册设备失败");
        }

        // 获取结果中的iot_id
        String iotId = response.getBody().getData().getIotId();

        // 查询IOT平台获取产品信息，将产品名称保存到设备对象
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        queryProductRequest.setProductKey(registerDeviceRequest.getProductKey());

        QueryProductResponse queryProductResponse;
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if(!queryProductResponse.getBody().getSuccess()){
            throw new BaseException("调用IOT平台获取产品信息失败");
        }
        // 产品查询成功
        String productName = queryProductResponse.getBody().getData().getProductName();
        // 属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(productName);
        // 设置iot_id
        device.setIotId(iotId);
        // 判断位置类型是否是0，如果是，设置物理位置类型为-1（老人）
        if(device.getLocationType() == 0){
            device.setPhysicalLocationType(-1);
        }
        try {
            // 报存设备到数据库
            save(device);
        } catch (RuntimeException e) {
            // 判断是否报存成功，如果失败了，则删除IOT平台设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setProductKey(registerDeviceRequest.getProductKey());
            deleteDeviceRequest.setDeviceName(registerDeviceRequest.getDeviceName());
            deleteDeviceRequest.setIotId(iotId);
            deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException("调用IOT平台删除设备失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 查询设备详情
     *
     * @param deviceDto 设备信息
     * @return 设备详情
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        // 根据产品Key和设备Id查询IOT平台获取设备详细信息
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setProductKey(deviceDto.getProductKey());
        request.setIotId(deviceDto.getIotId());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
             response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 获取响应中的数据
        if(!response.getBody().getSuccess()){
            throw new BaseException("调用IOT平台查询设备详情失败");
        }
        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        // 根据设备Id查询数据库获取设备信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, deviceDto.getIotId()));
        // 使用Vo类合并设备信息
        DeviceVo deviceVo = BeanUtil.toBean(device, DeviceVo.class);
        // 第三个参数的作用在复制过程中，如果 data 中的某个属性值为 null，则不会将这个 null 值赋给 deviceVo 中的对应属性。
        BeanUtil.copyProperties(data, deviceVo, CopyOptions.create().ignoreNullValue());
        // 返回合并后的数据
        return deviceVo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request 请求参数包含productKey
     * @return 结果
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        // 调用IOT平台接口查询结果
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if(!response.getBody().getSuccess()){
            throw new BaseException("调用IOT平台查询物模型失败");
        }
        // 查询成功返回结果
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request 请求对象包含设备名称和productKey
     * @return 结果
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        //调用IOT平台接口查询结果
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if(!response.getBody().getSuccess()) {
            throw new BaseException("调用IOT平台查询设备物模型运行状态失败");
        }

        // 查询成功返回结果
        return AjaxResult.success(response.getBody().getData());
    }


    /**
     * 修改设备备注
     *
     * @param device 设备信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDeviceRemark(Device device) {
        // 修改数据库的设备备注
        deviceMapper.updateById(device);

        // 构建请求对象以修改IOT平台的设备备注
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        // 设置IOT实例ID
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        // 初始化设备昵称信息列表
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list
                = new ArrayList<>();

        // 创建并配置设备昵称信息对象
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo
                = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setNickname(device.getNickname());
        nicknameInfo.setDeviceName(device.getDeviceName());
        nicknameInfo.setProductKey(device.getProductKey());

        // 将昵称信息添加到列表中
        list.add(nicknameInfo);
        // 设置请求对象的设备昵称信息
        request.setDeviceNicknameInfo(list);

        // 执行批量更新设备昵称的请求
        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            // 如果发生异常，转换为运行时异常重新抛出
            throw new RuntimeException(e);
        }

        // 验证响应是否成功，如果不成功则抛出自定义异常
        if (!response.getBody().getSuccess()){
            throw new BaseException("调用IOT平台修改设备备注失败");
        }
    }

    /**
     * 删除产品
     *
     * @param request 请求对象包含productKey和iotId
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deleteDevice(DeleteDeviceRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        // 删除数据库设备
        deviceMapper.delete(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, request.getIotId()));


        // 如果删除成功，调用IOT平台接口删除设备
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 判断是否删除成功
        if (!response.getBody().getSuccess()){
            throw new BaseException("调用IOT平台删除设备失败");
        }

        return AjaxResult.success();
    }
}
